package com.heima.search.service.impl;

import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.repository.ArticleRepository;
import com.heima.search.service.IApUserSearchService;
import com.heima.search.service.IArticleSearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class ArticleSearchServiceImpl implements IArticleSearchService {
    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private IApUserSearchService userSearchService;
    @Override
    public ResponseResult search(ApArticleSearchDto dto) {
        //如果搜索的关键字为空直接返回一个空的数据列表
        if (dto==null|| StringUtils.isEmpty(dto.getSearchWords())) {
            return new PageResponseResult(dto.getPage(), dto.getSize(), 0L, new ArrayList<ApArticleSearch>());
        }

        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", dto.getSearchWords());
        PageRequest pageRequest = PageRequest.of(dto.getPage().intValue() - 1, dto.getSize(), Sort.by(Sort.Direction.DESC, "publishTime"));
        Page<ApArticleSearch> searchPage = articleRepository.search(queryBuilder, pageRequest);
        PageResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),searchPage.getTotalElements(),searchPage.getContent());
        //异步包村用户的搜索记录  在启动类上添加注解   新建任务类  添加异步方法
        //获取当前用户
        User user = UserThreadLocalUtil.get();
        userSearchService.saveSearchRecord(dto.getSearchWords(), user.getUserId(), dto.getEquipmentId());
        return result;
    }
}
